package com.kk.crowd.mvc.config;


import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Objects;

@Component
public class PasswordEncoderService implements PasswordEncoder {
    // encode()方法对明文进行加密
    public String encode(CharSequence rawPassword) {
        return privateEncode (rawPassword);
    }

    // matches()方法对明文加密后和密文进行比较
    public boolean matches(CharSequence rawPassword, String encodedPassword) {

        // 1.对明文密码进行解密
        String formPassword = privateEncode (rawPassword);

        // 2.声明数据库密码
        String databasePassword = encodedPassword;

        // 3.比较
        return Objects.equals (formPassword, databasePassword);
    }

    // md5工具类，也可以在工程直接调用已有
    private static String privateEncode(CharSequence rawPassword) {
        try {
            // 1.创建MessageDigest对象
            String algorithm = "MD5";
            MessageDigest messageDigest = MessageDigest.getInstance (algorithm);

            // 2.获取rawPassword的字节数组
            byte[] input = ((String) rawPassword).getBytes ( );

            // 3.加密
            byte[] output = messageDigest.digest (input);

            // 4.转换为16进制数对应的字符
            String encoded = new BigInteger (1, output).toString (16).toUpperCase ( );
            return encoded;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace ( );
            return null;
        }
    }


}
